package com.yiwei.zxp.activity;

import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.allen.library.SuperButton;
import com.yiwei.zxp.R;
import com.yiwei.zxp.adapter.BuyerOrderDetailAdapter;
import com.yiwei.zxp.api.Api;
import com.yiwei.zxp.api.bean.BuyerOrderDetailBean;
import com.yiwei.zxp.api.model.BuyerOrderDetailModel;
import com.yiwei.zxp.api.model.ExpressCheckModel;
import com.yiwei.zxp.base.BaseActivity;
import com.yiwei.zxp.event.BuyerOrderNeedRefreshEvent;
import com.yiwei.zxp.util.Arith;
import com.yiwei.zxp.util.DateTime;
import com.yiwei.zxp.util.Dialog;
import com.yiwei.zxp.util.Network;
import com.yiwei.zxp.util.RxLifeUtil;
import com.yiwei.zxp.util.Spans;
import com.yiwei.zxp.util.ToastUtil;
import com.yiwei.zxp.util.UI;
import com.yiwei.zxp.util.Util;
import com.yiwei.zxp.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class BuyerOrderDetailActivity extends BaseActivity {


    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.txt_status)
    TextView txtStatus;
    @BindView(R.id.img_status)
    ImageView imgStatus;
    @BindView(R.id.layout_address_empty)
    FrameLayout layoutAddressEmpty;
    @BindView(R.id.txt_name_phone)
    TextView txtNamePhone;
    @BindView(R.id.txt_address)
    TextView txtAddress;
    @BindView(R.id.layout_address_data)
    FrameLayout layoutAddressData;
    @BindView(R.id.img_type)
    ImageView imgType;
    @BindView(R.id.txt_name)
    TextView txtName;
    @BindView(R.id.txt_left_info)
    TextView txtLeftInfo;
    @BindView(R.id.txt_right_info)
    TextView txtRightInfo;
    @BindView(R.id.txt_left_sec_info)
    TextView txtLeftSecInfo;
    @BindView(R.id.txt_right_sec_info)
    TextView txtRightSecInfo;
    @BindView(R.id.btn_submit)
    SuperButton btnSubmit;
    @BindView(R.id.txt_wuliu)
    TextView txtWuliu;
    @BindView(R.id.layout_wuliu)
    FrameLayout layoutWuliu;
    @BindView(R.id.list)
    RecyclerView list;
    @BindView(R.id.btn_submit_one)
    SuperButton btnSubmitOne;
    private Unbinder unbiner;
    private int x26;
    private BuyerOrderDetailAdapter adapter;
    private String order_no;
    private String shop_phone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buyer_order_detail);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
        order_no = getIntent().getStringExtra("order_no");
        getBuyerOrderDetail(order_no);
        getExpressCheck(order_no);
    }

    private void init() {
        x26 = getResources().getDimensionPixelSize(R.dimen.x26);
        txtTitle.setText("商品订单详情");
        list.setNestedScrollingEnabled(false);
        adapter = new BuyerOrderDetailAdapter(this);
        list.setAdapter(adapter);
    }

    public void getBuyerOrderDetail(String order_no) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        BuyerOrderDetailBean bean = new BuyerOrderDetailBean();
        bean.order_no = order_no;
        Api.api_service.getBuyerOrderDetail(bean).compose(RxLifeUtil.NocheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.code.equals("00")) {
                        setDetailData(result.datas);
                    }
                });
    }

    public void getBuyerOrderDelete(String order_no) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        BuyerOrderDetailBean bean = new BuyerOrderDetailBean();
        bean.order_no = order_no;
        Api.api_service.getBuyerOrderDelete(bean).compose(RxLifeUtil.loginCheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    Dialog.showDefaultDialog(this, "", "是否确定删除该订单？", "取消", "确定", false, new Dialog.DialogDefaultClickListener() {
                        @Override
                        public void confirm() {
                            EventBus.getDefault().post(new BuyerOrderNeedRefreshEvent());
                            ToastUtil.makeText(BuyerOrderDetailActivity.this, "删除成功");
                            finish();
                        }

                        @Override
                        public void cancel() {

                        }
                    });
                });
    }

    public void getExpressCheck(String order_no) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        BuyerOrderDetailBean bean = new BuyerOrderDetailBean();
        bean.order_no = order_no;

        Api.api_service.getExpressCheck(bean).compose(RxLifeUtil.NocheckOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.code.equals("00")) {
                        ExpressCheckModel.DatasBean item = result.datas;
                        if (item.result != null && item.result.size() != 0) {
                            Spanned txt_info = Spans.with(this).font(item.result.get(0).status, getResources().getDimensionPixelSize(R.dimen.x28), 0xff4CD127).
                                    font("\n" + item.result.get(0).time, getResources().getDimensionPixelSize(R.dimen.x24), 0xff999999).
                                    build();
                            txtWuliu.setText(txt_info);
                        } else {
                            txtWuliu.setText("暂无物流信息");
                        }
                    } else {
                        txtWuliu.setText("暂无物流信息");
                    }

                });
    }

    public void getBuyerOrderSure(String order_no) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        BuyerOrderDetailBean bean = new BuyerOrderDetailBean();
        bean.order_no = order_no;
        Api.api_service.getOrderComplete(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    ToastUtil.makeText(this, "确认收货成功");
                    EventBus.getDefault().post(new BuyerOrderNeedRefreshEvent());
                    finish();
                });
    }

    private void setDetailData(BuyerOrderDetailModel.DatasBean datas) {
        BuyerOrderDetailModel.DatasBean.OrderInfoBean orderInfo = datas.order_info;
        shop_phone = datas.shop_info.shop_phone;
        Spanned txt_left = Spans.with(this).font("商品数量", x26, 0xff999999).
                font("\n商品总价", x26, 0xff999999).
                font("\n淘淘币共抵扣", x26, 0xff999999).
                font("\n总运费", x26, 0xff999999).
                font("\n实际应付金额", x26, 0xff010101).
                build();
        txtLeftInfo.setText(txt_left);

        Spanned txt_right = Spans.with(this).font(orderInfo.num, x26, 0xff999999).
                font("\n￥" + orderInfo.money, x26, 0xff999999).
                font("\n-￥" + orderInfo.shared_gold, x26, 0xff999999).
                font("\n￥" + orderInfo.deliver_fee, x26, 0xff999999).
                font("\n￥" + Arith.add(Double.valueOf(orderInfo.true_money), Double.valueOf(orderInfo.deliver_fee)), x26, 0xffFF0030).style(Typeface.BOLD).
                build();
        txtRightInfo.setText(txt_right);


        adapter.update(datas.items);
        txtName.setText(datas.shop_info.shop_name);

        BuyerOrderDetailModel.DatasBean.AddressInfoBean addressInfo = datas.address_info;
        txtNamePhone.setText(addressInfo.name + "   " + addressInfo.phone);
        txtAddress.setText((addressInfo.province == null ? "" : addressInfo.province) +
                (addressInfo.city == null ? "" : addressInfo.city) +
                (addressInfo.district == null ? "" : addressInfo.district) +
                (addressInfo.address == null ? "" : addressInfo.address));
        //状态（-1：失效，0：待付款，1：已付款/待发货，2：已发货，3：待评论，4：已完成）
        switch (orderInfo.status) {
            case "-1":
                txtStatus.setText("交易已关闭");
                imgStatus.setImageResource(R.mipmap.img_status_close);
                btnSubmit.setVisibility(View.GONE);
                btnSubmitOne.setText("删除订单");
                btnSubmitOne.setVisibility(View.VISIBLE);
                Spanned txt_left_sec01 = Spans.with(this).font("订单编号", x26, 0xff999999).
                        font("\n下单时间", x26, 0xff999999).
                        build();
                txtLeftSecInfo.setText(txt_left_sec01);

                Spanned txt_right_sec01 = Spans.with(this).font(orderInfo.order_no, x26, 0xff999999).
                        font("\n" + DateTime.toDateTime(Long.valueOf(orderInfo.created_at) * 1000), x26, 0xff999999).
                        build();
                txtRightSecInfo.setText(txt_right_sec01);
                break;
            case "0":
                String restTime = Util.getRestTime(Long.valueOf(datas.order_info.valid_time) * 1000 - new Date().getTime());
                Spanned rest_time = Spans.with(this).font("等待买家付款\n", getResources().getDimensionPixelSize(R.dimen.x32), 0xffffffff).
                        font("剩" + restTime + "自动关闭", getResources().getDimensionPixelSize(R.dimen.x24), 0xffffffff).style(Typeface.BOLD).
                        build();
                txtStatus.setText(rest_time);
                imgStatus.setImageResource(R.mipmap.img_status_need_pay);
                btnSubmit.setText("付款");
                btnSubmit.setVisibility(View.VISIBLE);
                btnSubmitOne.setVisibility(View.GONE);
                Spanned txt_left_sec0 = Spans.with(this).font("订单编号", x26, 0xff999999).
                        font("\n下单时间", x26, 0xff999999).
                        build();
                txtLeftSecInfo.setText(txt_left_sec0);

                Spanned txt_right_sec0 = Spans.with(this).font(orderInfo.order_no, x26, 0xff999999).
                        font("\n" + DateTime.toDateTime(Long.valueOf(orderInfo.created_at) * 1000), x26, 0xff999999).
                        build();
                txtRightSecInfo.setText(txt_right_sec0);
                break;
            case "1":
                txtStatus.setText("等待卖家发货");
                imgStatus.setImageResource(R.mipmap.img_status_need_send);
                btnSubmit.setText("提醒发货");
                btnSubmit.setVisibility(View.VISIBLE);
                btnSubmitOne.setVisibility(View.VISIBLE);
                btnSubmitOne.setText("联系商家");
                Spanned txt_left_sec1 = Spans.with(this).font("订单编号", x26, 0xff999999).
                        font("\n下单时间", x26, 0xff999999).
                        font("\n支付方式", x26, 0xff999999).
                        font("\n支付时间", x26, 0xff999999).
                        build();
                txtLeftSecInfo.setText(txt_left_sec1);

                Spanned txt_right_sec1 = Spans.with(this).font(orderInfo.order_no, x26, 0xff999999).
                        font("\n" + DateTime.toDateTime(Long.valueOf(orderInfo.created_at) * 1000), x26, 0xff999999).
                        font("\n" + getPayWay(orderInfo.pay_way), x26, 0xff999999).
                        font("\n" + DateTime.toDateTime(Long.valueOf(orderInfo.pay_time) * 1000), x26, 0xff999999).
                        build();
                txtRightSecInfo.setText(txt_right_sec1);
                break;
            case "2":
                txtStatus.setText("卖家已发货");
                imgStatus.setImageResource(R.mipmap.img_status_has_send);
                btnSubmit.setText("确认收货");
                btnSubmit.setVisibility(View.VISIBLE);
                btnSubmitOne.setText("查看物流");
                btnSubmitOne.setVisibility(View.VISIBLE);
                Spanned txt_left_sec2 = Spans.with(this).font("订单编号", x26, 0xff999999).
                        font("\n下单时间", x26, 0xff999999).
                        font("\n支付方式", x26, 0xff999999).
                        font("\n支付时间", x26, 0xff999999).
                        font("\n发货时间", x26, 0xff999999).
                        build();
                txtLeftSecInfo.setText(txt_left_sec2);

                Spanned txt_right_sec2 = Spans.with(this).font(orderInfo.order_no, x26, 0xff999999).
                        font("\n" + DateTime.toDateTime(Long.valueOf(orderInfo.created_at) * 1000), x26, 0xff999999).
                        font("\n" + getPayWay(orderInfo.pay_way), x26, 0xff999999).
                        font("\n" + DateTime.toDateTime(Long.valueOf(orderInfo.pay_time) * 1000), x26, 0xff999999).
                        font("\n" + DateTime.toDateTime(Long.valueOf(orderInfo.send_time) * 1000), x26, 0xff999999).
                        build();
                txtRightSecInfo.setText(txt_right_sec2);
                layoutWuliu.setVisibility(View.VISIBLE);
                break;
            case "3":
                txtStatus.setText("待评论");
                imgStatus.setImageResource(R.mipmap.img_status_goods_finish);
                btnSubmit.setVisibility(View.VISIBLE);
                btnSubmit.setText("评价");
                btnSubmitOne.setText("删除订单");
                btnSubmitOne.setVisibility(View.VISIBLE);
                Spanned txt_left_sec3 = Spans.with(this).font("订单编号", x26, 0xff999999).
                        font("\n下单时间", x26, 0xff999999).
                        font("\n支付方式", x26, 0xff999999).
                        font("\n支付时间", x26, 0xff999999).
                        font("\n发货时间", x26, 0xff999999).
                        font("\n完成时间", x26, 0xff999999).
                        build();
                txtLeftSecInfo.setText(txt_left_sec3);

                Spanned txt_right_sec3 = Spans.with(this).font(orderInfo.order_no, x26, 0xff999999).
                        font("\n" + DateTime.toDateTime(Long.valueOf(orderInfo.created_at) * 1000), x26, 0xff999999).
                        font("\n" + getPayWay(orderInfo.pay_way), x26, 0xff999999).
                        font("\n" + DateTime.toDateTime(Long.valueOf(orderInfo.pay_time) * 1000), x26, 0xff999999).
                        font("\n" + DateTime.toDateTime(Long.valueOf(orderInfo.send_time) * 1000), x26, 0xff999999).
                        font("\n" + DateTime.toDateTime(Long.valueOf(orderInfo.complete_time) * 1000), x26, 0xff999999).
                        build();
                txtRightSecInfo.setText(txt_right_sec3);
                layoutWuliu.setVisibility(View.VISIBLE);
                break;
            case "4":
                txtStatus.setText("交易已完成");
                imgStatus.setImageResource(R.mipmap.img_status_goods_finish);
                btnSubmit.setVisibility(View.VISIBLE);
                btnSubmit.setText("查看评价");
                btnSubmitOne.setText("删除订单");
                btnSubmitOne.setVisibility(View.VISIBLE);
                Spanned txt_left_sec4 = Spans.with(this).font("订单编号", x26, 0xff999999).
                        font("\n下单时间", x26, 0xff999999).
                        font("\n支付方式", x26, 0xff999999).
                        font("\n支付时间", x26, 0xff999999).
                        font("\n发货时间", x26, 0xff999999).
                        font("\n完成时间", x26, 0xff999999).
                        build();
                txtLeftSecInfo.setText(txt_left_sec4);

                Spanned txt_right_sec4 = Spans.with(this).font(orderInfo.order_no, x26, 0xff999999).
                        font("\n" + DateTime.toDateTime(Long.valueOf(orderInfo.created_at) * 1000), x26, 0xff999999).
                        font("\n" + getPayWay(orderInfo.pay_way), x26, 0xff999999).
                        font("\n" + DateTime.toDateTime(Long.valueOf(orderInfo.pay_time) * 1000), x26, 0xff999999).
                        font("\n" + DateTime.toDateTime(Long.valueOf(orderInfo.send_time) * 1000), x26, 0xff999999).
                        font("\n" + DateTime.toDateTime(Long.valueOf(orderInfo.complete_time) * 1000), x26, 0xff999999).
                        build();
                txtRightSecInfo.setText(txt_right_sec4);
                layoutWuliu.setVisibility(View.VISIBLE);
                break;
        }
    }


    public String getPayWay(String pay_way) {
//（0：淘淘币支付全额,1:线下，2：银行卡）
        switch (pay_way) {
            case "0":
                return "淘淘币支付全额";
            case "1":
                return "线下";
            case "2":
                return "银行卡";
            default:
                return "";
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbiner.unbind();
        unbiner = null;
    }

    @OnClick({R.id.layout_wuliu, R.id.btn_back, R.id.btn_submit_one, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_wuliu:
                Intent intentWuliu = new Intent(this, LogisticsActivity.class);
                intentWuliu.putExtra("order_no", order_no);
                startActivity(intentWuliu);
                break;
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_submit_one:
                if (UI.toString(btnSubmitOne).equals("删除订单")) {
                    Dialog.showDefaultDialog(this, "", "是否确定删除该订单？", "取消", "确定", false, new Dialog.DialogDefaultClickListener() {
                        @Override
                        public void confirm() {
                            getBuyerOrderDelete(order_no);
                        }

                        @Override
                        public void cancel() {

                        }
                    });
                } else if (UI.toString(btnSubmitOne).equals("查看物流")) {
                    Intent intent = new Intent(this, LogisticsActivity.class);
                    intent.putExtra("order_no", order_no);
                    startActivity(intent);
                    overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                } else if (UI.toString(btnSubmitOne).equals("联系商家")) {
                    Dialog.showDefaultDialog(this, "", "联系客服\n" + shop_phone, "取消", "呼叫", false, new Dialog.DialogDefaultClickListener() {
                        @Override
                        public void confirm() {
                            Intent intentCall = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + shop_phone));
                            intentCall.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intentCall);
                        }

                        @Override
                        public void cancel() {

                        }
                    });
                }
                break;
            case R.id.btn_submit:
                if (UI.toString(btnSubmit).equals("确认收货")) {
                    Dialog.showDefaultDialog(this, "", "是否确认收货？", "取消", "确定", false, new Dialog.DialogDefaultClickListener() {
                        @Override
                        public void confirm() {
                            getBuyerOrderSure(order_no);
                        }

                        @Override
                        public void cancel() {

                        }
                    });

                } else if (UI.toString(btnSubmit).equals("查看评价")) {
                    Util.startActivity(this, MyCommentActivity.class);
                } else if (UI.toString(btnSubmit).equals("提醒发货")) {
                    ToastUtil.makeText(this, "提醒成功");
                } else if (UI.toString(btnSubmit).equals("付款")) {
                    ArrayList<String> data = new ArrayList<>();
                    data.add(order_no);
                    Intent intent = new Intent(this, PayTypeActivity.class);
                    intent.putStringArrayListExtra("data", data);
                    startActivity(intent);
                    finish();
                } else if (UI.toString(btnSubmit).equals("评价")) {
                    Intent intent = new Intent(this, SendEvaluateActivity.class);
                    intent.putExtra("order_no", order_no);
                    startActivity(intent);
                    overridePendingTransition(R.anim.right_enter, R.anim.left_out);
                    finish();
                }
                break;
        }
    }
}
